/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.zkex.list.menu;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.vos.datalist.ListHeaderVo;
import cn.easyplatform.type.FieldType;
import cn.easyplatform.web.task.zkex.list.GroupableListSupport;
import cn.easyplatform.web.task.zkex.list.group.Group;
import cn.easyplatform.web.task.zkex.list.group.ReportGroup;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zk.ui.event.OpenEvent;
import org.zkoss.zul.*;

import java.util.Iterator;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class GroupColumnMenu extends Menupopup implements ColumnMenu {
    /**
     *
     */
    private static final long serialVersionUID = -4481997711038925156L;

    private transient GroupableListSupport support;

    private transient Column _ref;

    private transient Group _group;

    private transient boolean _isSameGroup;

    public GroupColumnMenu(final Columns cols, GroupableListSupport support) {
        this.support = support;
        setPage(cols.getPage());
        addEventListener(Events.ON_OPEN, new EventListener<OpenEvent>() {
            public void onEvent(OpenEvent event) throws Exception {
                if (event.isOpen()) {
                    _ref = (Column) event.getReference();
                    if (_group != GroupColumnMenu.this.support.getGroup()) {
                        _isSameGroup = false;
                        _group = GroupColumnMenu.this.support.getGroup();
                    } else
                        _isSameGroup = true;
                    init(cols);
                }
            }
        });
    }

    private void init(Columns cols) {
        if (getChildren().isEmpty()) {
            // 显示层级
            Menu display = new Menu(Labels.getLabel("datalist.show"));
            display.setIconSclass("z-icon-list-ol z-menu-image");
            createDisplayMenu(display);
            display.setParent(this);

            // 分组
            Menu group = new Menu(Labels.getLabel("datalist.group"));
            group.setIconSclass("z-icon-align-center z-menu-image");
            createGroupMenuPopup(group);
            group.setParent(this);
            // 导出
            Menuitem export = new Menuitem(Labels.getLabel("button.export"));
            export.setAttribute("id", "--exp--");
            export.setIconSclass("z-icon-share z-menu-image");
            export.setParent(this);
            export.addEventListener(Events.ON_CLICK, support);
            export.setVisible(support.getEntity().isExport());

            // 过滤
            Menuitem filter = new Menuitem(Labels.getLabel("datalist.filter"));
            filter.setAttribute("id", "--filter--");
            filter.setIconSclass("z-icon-filter z-menu-image");
            filter.setParent(this);
            filter.addEventListener(Events.ON_CLICK, support);

            Menuseparator sep = new Menuseparator();
            sep.setParent(this);

            //栏位
            Menu columns = new Menu(Labels.getLabel("datalist.columns"));
            columns.setIconSclass("z-icon-align-justify z-menu-image");
            columns.setParent(this);
            Menupopup mp = new Menupopup();
            mp.setParent(columns);
            List<Column> children = cols.getChildren();
            for (final Column col : children) {
                if (Strings.isBlank(col.getLabel()))
                    continue;
                final Menuitem item = new Menuitem(col.getLabel());
                item.setAutocheck(true);
                item.setCheckmark(true);
                item.setChecked(col.isVisible());
                item.addEventListener(Events.ON_CLICK,
                        new EventListener<Event>() {
                            public void onEvent(Event event) throws Exception {
                                Menupopup pop = (Menupopup) item.getParent();
                                int checked = 0;
                                for (Iterator<?> it = pop.getChildren()
                                        .iterator(); it.hasNext(); ) {
                                    Object obj = it.next();
                                    if (obj instanceof Menuitem
                                            && ((Menuitem) obj).isChecked()) {
                                        checked++;
                                    }
                                }
                                if (checked == 0) {
                                    item.setChecked(true);
                                }
                                col.setVisible(item.isChecked());
                            }
                        });
                item.setParent(mp);
            }
        } else if (!_isSameGroup) {
            getFirstChild().getChildren().clear();
            createDisplayMenu(getFirstChild());
        }
        ListHeaderVo hv = _ref.getValue();
        if (hv != null && !Strings.isBlank(hv.getField())
                && hv.getType() != FieldType.BLOB
                && hv.getType() != FieldType.CLOB
                && hv.getType() != FieldType.OBJECT) {
            getChildren().get(3).setVisible(true);
        } else {
            getChildren().get(3).setVisible(false);
        }
    }

    private void createDisplayMenu(Component parent) {
        Menupopup mp = new Menupopup();
        ReportGroup group = support.getGroup();
        Menuitem mi = new Menuitem(Labels.getLabel("datalist.show.all"));
        mi.setAutocheck(true);
        mi.setCheckmark(true);
        mi.setChecked(true);
        mi.setAttribute("id", "show_" + group.getMaxLevel());
        mi.addEventListener(Events.ON_CLICK, support);
        mp.appendChild(mi);

        for (int i = 0; i < group.getMaxLevel(); i++) {
            mi = new Menuitem(Labels.getLabel("datalist.show.level",
                    new Object[]{i + 1}));
            mi.setAutocheck(true);
            mi.setCheckmark(true);
            mi.setAttribute("id", "show_" + i);
            mi.addEventListener(Events.ON_CLICK, support);
            mp.appendChild(mi);
        }

        mi = new Menuitem(Labels.getLabel("datalist.show.none"));
        mi.setAutocheck(true);
        mi.setCheckmark(true);
        mi.setAttribute("id", "show_-1");
        mi.addEventListener(Events.ON_CLICK, support);
        mp.appendChild(mi);
        parent.appendChild(mp);
    }

    private void createGroupMenuPopup(Component group) {
        Menupopup mp = new Menupopup();
        List<ReportGroup> gl = support.getGroups();
        int index = 0;
        for (ReportGroup gp : gl) {
            Menuitem mi = new Menuitem(gp.getTitle());
            mi.setAutocheck(true);
            mi.setCheckmark(true);
            mi.addEventListener(Events.ON_CLICK, support);
            mi.setAttribute("id", "group_" + index);
            mp.appendChild(mi);
            index++;
        }
        ((Menuitem) mp.getFirstChild()).setChecked(true);
        group.appendChild(mp);
        Menuseparator sep = new Menuseparator();
        sep.setParent(mp);
        Menuitem mi = new Menuitem(Labels.getLabel("datalist.group.user"));
        mi.setAttribute("id", "group_user");
        mi.addEventListener(Events.ON_CLICK, support);
        mi.setIconSclass("z-icon-legal z-menu-image");
        mi.setParent(mp);
    }

    public ListHeaderVo getHeader() {
        return _ref.getValue();
    }

    public Object clone() {
        final GroupColumnMenu clone = (GroupColumnMenu) super.clone();
        clone.support = null;
        return clone;
    }
}
